<template>
	<el-row >
		<!-- 主体表单 -->
		<el-row>
			<!-- 项目基本信息 -->
			<el-col :md='24' :lg='10' align='left'>
				<!-- tab -->
				<el-tabs v-model="fir_activeName" >
	    			<el-tab-pane label="项目信息" ></el-tab-pane>
	    		</el-tabs>
	    		<el-col  :xs='24' :sm='{span:16,offset:2}' :md='{span:14,offset:2}' :lg='{span:20,offset:0}'>
					<el-form  ref="form"  :model="form"  :rules='rules'  label-width="170px"  :label-position="labelPosition"  size='small'>
						<el-form-item   label="项目名称："   prop='prjName'>
						    <el-input   v-model="form.prjName" placeholder='请输入项目名称'></el-input>
						</el-form-item>
						<el-form-item   class='rule_proName'>
						    <span>项目命名规则：产品类型-承销商〈四个字以内的缩写〉-发行人〈四个字以内的缩写〉(六位数年月日)【示例： 定项融资工具-恒大金服-恒大-190710】</span>
						</el-form-item>
						<el-form-item   label="项目类型："  prop='prjType'>
					  		<el-select v-model="form.prjType" placeholder="请选择" class='w-100'>
							    <el-option
							      v-for="item in pro_type"
							      :key="item.value"
							      :label="item.label"
							      :value="item.value">
							    </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="项目规模："  prop='prjSize'>
						    <el-input v-model="form.prjSize"  type='number'  class='number_right'><template slot="suffix">万元</template></el-input>
						</el-form-item>
						<el-form-item label="融资主体性质："  prop='financingSubjectNature'>
					    	<el-select v-model="form.financingSubjectNature" placeholder="请选择" class='w-100'>
							    <el-option
							      v-for="item in rongzi_type"
							      :key="item.value"
							      :label="item.label"
							      :value="item.value">
							    </el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="所属集团：" >
						    <el-input v-model="form.affiliatedGroup"  placeholder='请输入所属集团'></el-input>
						</el-form-item>
						<el-form-item label="项目负责人："  prop='principalCode'>
					    	<el-select v-model="form.principalCode"  placeholder="搜索选择" filterable class='w-100'  >
				                <el-option
				                  v-for="(item,index) in pro_userlist"
				                  :key="item.code"
				                  :label="item.name"
				                  :disabled="item.useable == 0"
				                  :value="item.code">
				                </el-option>
					          </el-select>
						</el-form-item>
						<el-form-item label="项目对接人："  prop='dockerCode'>
					    	<el-select v-model="form.dockerCode"  placeholder="搜索选择" filterable class='w-100'  >
				                <el-option
				                  v-for="(item,index) in pro_userlist"
				                  :key="item.code"
				                  :label="item.name"
				                  :disabled="item.useable == 0"
				                  :value="item.code">
				                </el-option>
					          </el-select>
						</el-form-item>
						<el-form-item      label="项目存续周期不超过："  prop='subsistingCycle'>
						    <el-input v-model="form.subsistingCycle" placeholder='请输入'  type='number'><template slot="suffix">月</template></el-input>
						</el-form-item>
							<el-form-item label="募集对象：" >
						    <el-input v-model="form.recruitmentObject"  placeholder='请输入'></el-input>
						</el-form-item>
						<el-form-item      label="募集金额："  prop='collectionAmt'>
							<el-input  v-model="form.collectionAmt" placeholder='请输入'  type='number'  class='number_right'>   <template slot="suffix"> 万元</template></el-input>
					        <el-radio v-model="form.collectionAmtType"   label="2" >场外</el-radio>
					        <el-radio v-model="form.collectionAmtType"   label="1" >场内</el-radio>
						</el-form-item>
						<el-form-item label="募集速度：" >
						    <el-input v-model="form.collectionVelocity"  placeholder='请输入'><template slot="suffix">销售额/月</template></el-input>
						</el-form-item>
						<el-form-item label="交易所拟收费标准："  prop='chargesStandard'>
					    	<el-input  v-model="form.chargesStandard"  placeholder='请输入'  class='inline-block'><template slot="suffix">%</template></el-input>
					    	<el-radio  v-model="form.chargesMethod"  label="1" >年化收取</el-radio>
					        <el-radio  v-model="form.chargesMethod"  label="2" >单笔收取</el-radio>
						</el-form-item>
						<el-form-item      label="收费方式："  prop='chargingMethod' >
							<el-radio-group v-model="form.chargingMethod">
						    	<el-radio    label="1" >前置</el-radio>
				                <el-radio    label="2" >按季</el-radio>
				                <el-radio    label="3" >按月</el-radio>
				                <el-radio    label="4" >其他</el-radio>
						    </el-radio-group>
					        <el-input v-if='form.chargingMethod == 4'  v-model='form.chargingValue' placeholder='请输入' ></el-input>
						</el-form-item>
						<el-form-item      label="期望挂牌完成日期：" >
						    <el-date-picker
						      v-model="form.expCompleteDate"
						      type="date"
						      placeholder="选择日期">
						    </el-date-picker>
						</el-form-item>
						<el-form-item   label='其他备注信息：'>
						  	<el-input v-model.trim="form.comments" placeholder='请输入内容' type='textarea' rows='5' ></el-input>
						</el-form-item>
					</el-form>
				</el-col>
			</el-col>	
			<!-- 企业、文件、相关人员 -->
			<el-col :md='24' :lg='{span:13,offset:1}' align='left'>
				<!-- 企业 -->
				<el-row>
					<el-tabs v-model="fir_activeName" >
		    			<el-tab-pane label="参与企业" name="first"></el-tab-pane>
		    		</el-tabs>
		            <el-button type="primary" icon="el-icon-plus" size="small" round  @click="joinCompanyAdd()"  class='mb16'>添加</el-button>
		            <el-table :data="company_list" >     
						<el-table-column  prop="entRole" label="项目角色"  align='center'>
							<template slot-scope='list'>
								{{list.row.entRole | pro_comRole}}
							</template>
						</el-table-column>
						<el-table-column  prop='entName' label="企业名称" align='center'></el-table-column>
						<el-table-column  prop='' label="收费方式" align='center'>
							<template slot-scope='list'>
								{{list.row.chargingMethod | pro_comCharge}}
							</template>
						</el-table-column>
						<el-table-column  prop='serviceRate' label="服务费率" align='center'>
							<template slot-scope='list'>	
								<el-row  v-if='list.row.serviceRate'>{{list.row.serviceRate}}%</el-row>
					  			<el-row  v-else>--</el-row>
							</template>
						</el-table-column>
						<el-table-column  prop='bizEntBankList' label="账号信息" align='center'>
							<template slot-scope='list'>
								<el-row  v-if='list.row.bizEntBankList.length'>
									<li v-for='item in list.row.bizEntBankList'>
											<div>{{item.bankAccount}} </div>
			      							{{item.accountName + item.subbranchName}}
									</li>
								</el-row>
								<el-row  v-else>暂无</el-row>
							</template>
						</el-table-column>
						<el-table-column   label="操作" align='center' width='150'>
						    <template v-slot="list">
						        <el-button  type="primary" size="mini" round @click="EditCompany(list.$index,list.row)">编辑</el-button>
						        <el-button  type="danger"  size="mini" round @click="delCompany( list.row.code)">删除</el-button>
						    </template>
						</el-table-column>       
		            </el-table>
		        </el-row>
		        <!-- 文件 -->
		        <el-row class='mt28'>
	        		<el-tabs v-model="fir_activeName" >
		    			<el-tab-pane label="项目材料" name="first"></el-tab-pane>
		    		</el-tabs>	
		    		<el-button type="primary" icon="el-icon-plus" size="small" round  @click="addFiles"  class='mb16'>添加</el-button>
		    		<el-table
                        :data="filelist"
                        header-row-class-name='bankheader' 
                        style="width: 100%">
                        <el-table-column  prop="fileName" label="文件名称"  align='center'></el-table-column>
                        <el-table-column   label="操作" align='center'>
                            <template v-slot="list">
                                <el-button  type="primary" size="mini" round @click="downloadFile( list.row.fileCode)">下载</el-button>
                                <el-button  type="danger"  size="mini" round @click="fileDelete( list.$index)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
		        </el-row>
		        <!-- 相关人员 -->
	            <el-row class='mt28'>
            		<el-tabs v-model="fir_activeName" >
		    			<el-tab-pane label="相关人员" name="first"></el-tab-pane>
		    		</el-tabs>	
		    		<el-button type="primary" icon="el-icon-plus" size="small" round  @click="addRelatedUser()"  class='mb16'>添加</el-button>
		    		<el-row>
						<dl v-for="(tag,index) in related_tags" class='fl ft14 mr30' align='center'>
							<dt class='mb10'>
								<img src='static/img/user/icon-default-user.png' title='用户头像' class='default-user-img'>
								<span><i class="el-icon-circle-close ft18 color-red cursor" type='' @click.prevent="close_related(index)"></i></span>
							</dt>
							<dd class='pr20'>{{tag.name}}</dd>
							<dd class='pr20'>{{tag.roleName}}</dd>
						</dl>
					</el-row>
	            </el-row>
			</el-col>
		</el-row>
		<el-row  class="dialog-footer mt42">
			<el-button @click="common_goback()">取 消</el-button>
			<el-button type="primary" @click="submit('form')"  :loading='displayLoading' >确 定</el-button>
        </el-row>
		<!-- 新增 参与企业 -->
        <CompanyEdit ref='addCompany' :companyList='companyList' v-on:save-finished='companyFinished(arguments)'> </CompanyEdit>
		<!-- 新增 文件 -->
        <FileEdit ref='addFile'  v-on:save='recept(arguments)'> </FileEdit>
        <!-- 新增 x相关人员 -->
        <relatedUserEdit ref='relatedUser' v-on:save-finished='relatedFinish($event)' > </relatedUserEdit>
        
	</el-row>
</template>

<script type="text/javascript">
/*interface*/
import { saveProject,detailProject,modifyProject }  from  '@/api/professional_work/project/index'
import { DetailCompany,listCompany } from '@/api/company/index'//company
import { listUser } from '@/api/user/index'//user
/*components*/
import FileEdit  from '@/components/common/FileEdit'//addfiles
import CompanyEdit  from '@/components/professional_work/project/CompanyEdit'//参与企业
import relatedUserEdit  from '@/components/professional_work/project/relatedUserEdit'//相关人员
export default {
	name: 'addProject',
	data(){
		let checkChargingMethod =(rule, value,  callback) => {
			if(value == 4){
				if(!this.form.chargingValue){
		        	return callback(new Error('请输入其他收费方式'));
		        }
		        else{
		        	callback();
		        }
			}
			else{
				callback();
			}
	    };
	    let checkCollectionAmt =(rule, value,  callback) => {
	        if(!this.form.collectionAmtType){
	        	return callback(new Error('请选择募集路径'));
	        }
	        else{
	        	callback();
	        }
	    };
	    let checkChargesStandard = (rule, value,  callback) => {
	        if(!this.form.chargesMethod){
	        	return callback(new Error('请选择收费方式'));
	        }
	        else{
	        	callback();
	        }
	    };
		return {
			/*static*/
			fir_activeName:'first',//tab高亮
			labelPosition:'right',//label对齐方式
      		//项目类型选项
			pro_type:[
                {value: '1',label: '收益权类'}, 
                {value: '2',label: '定向融资类'}, 
                {value: '3',label: '资产登记交易类'}, 
                {value: '4',label: '资产转让增值'},
                {value: '5',label: '其他类'}],
			//融资主体性质
			rongzi_type:[
				{value: '1',label: '政信'},
                {value: '2',label: '地产'}, 
                {value: '3',label: '国企'}, 
                {value: '4',label: '其他行业龙头'}
			],
			//获取企业列表
			companyList:[],
			//获取的用户列表
			pro_userlist:[],
			/*active*/
			form:{
				prjName:'',
				prjType:'',
				prjSize:'',
				financingSubjectNature:'',//融资主体
				affiliatedGroup:'',
				principalCode:'',
				dockerCode:'',

				subsistingCycle:'',
				subsistingCycleUnit:'1',

				recruitmentObject:'',
				collectionAmt:'',
				collectionVelocity:'',
				chargesStandard:'',

				chargingMethod:'',
				expCompleteDate:'',
				
				comments:'',

				projectEntList:[],//参与企业列表
				projectFileList:[],//项目材料
				userList:[],//相关人员
			},
			//编辑填写的企业list
			company_list:[],
			//上传的文件list
			filelist:[],
			//选中的相关人员list
			related_tags:[],
			//form-rules
			rules:{
				prjName:[
					{required:true,message:'请输入项目名称'}
				],
				prjType:[
					{required:true,message:'请选择项目类型'}
				],
				prjSize:[
					{required:true,message:'请输入项目规模'}
				],
				financingSubjectNature:[
					{required:true,message:'请选择融资主体性质'}
				],
				principalCode:[
					{required:true,message:'请选择项目负责人'}
				],
				dockerCode:[
					{required:true,message:'请选择项目对接人'}
				],
				subsistingCycle:[
					{required:true,message:'请输入项目存续周期'}
				],
				collectionAmt:[
					{required:true,message:'请输入募集金额'},
					{ validator: checkCollectionAmt, trigger: 'change' }
				],
				chargingMethod:[ //用于验证一个label验证两个必填项
					{required:true,message:"请选择收费方式"},
					{ validator: checkChargingMethod, trigger: 'change' }
				],
				chargesStandard:[
					{required:true,message:'请输入收费标准'},
					{ validator: checkChargesStandard, trigger: 'change' }
				],
			},

			isEdit:false,
			displayLoading: false,//按钮等待状态显示
			submitSuccess:false,//新增成功 编辑成功 =>清除缓存；取消编辑 返回上一页 =>仍然保持原页面
		}
	},
	created(){
		//网页宽度判断，更改布局
	    let clientWidth = document.body.clientWidth
	    if(clientWidth<600){
	    	this.labelPosition='top'
	    }

		this.pageInit()
		//设置初始为新增状态
		this.isEdit = false
		if(this.$route.query.code){
			this.isEdit = true
			detailProject(this.$route.query.code).then(res=>{
				//base
				this.form = res.data.data
				//参与企业列表
				this.company_list = this.form.projectEntList
				//相关材料
				this.filelist = this.form.projectFileList
				//相关人员
				this.related_tags  =  this.form.userList
				
			})
		}
	},
	methods:{
		/*初始化 页面  S*/
		async pageInit(){
		    let that =this
		    Promise.all([listUser({limit: 100,currentPage:1}),listCompany({limit:1000,currentPage:1})]).then((result) => {
		    	/*用户*/
		    	/*去除开发部和系统管理员*/
	        	result[0].data.dataList.forEach((item)=>{
	        		if(item.officeName != '技术部'  &&  item.officeCode != 'root'){
	        			this.pro_userlist.push(item)
	        		}
	        	})
	        	/*企业列表接口*/
	        	this.companyList = result[1].data.dataList
	        }).catch((error) => {
	            console.log(error)      
	        })
		   
		},
		/*初始化 页面  E*/

		/*表单操作 submit & 新增企业 账户 文件 相关角色  S*/
		submit(formName){
			let that = this
			this.$refs[formName].validate(valid => {
				if(valid){
					this.displayLoading = true
					//企业list 处理
					let up_company_list =[]
					this.company_list.forEach((item)=>{
						up_company_list.push({
							entCode:item.entCode,
							entRole:item.entRole,
							serviceRate:item.serviceRate,
							chargingMethod:item.chargingMethod,
						})
					})
					//相关材料list  处理
					let up_file_list = []
					this.filelist.forEach((item)=>{
						up_file_list.push({
							fileCode:item.fileCode,
							fileName:item.fileName,
						})
					})
					//企业回填
					this.form.projectEntList=up_company_list  
					//相关文件回填 
					this.form.projectFileList=up_file_list 
					//相关用户回填
					this.form.userList=this.related_tags
					if(this.isEdit == false){
						saveProject(this.form).then(res=>{
							if(res.data.flag == true){
									this.submitSuccess = true
									// this.$store.commit('cacheRoute',this.$store.state.cacheRoute.splice('item',1))
									this.$message({type:'success',message:res.data.msg})
									this.$router.push({name:'item'})
							}
							else{
								setTimeout(function(){
			                          that.displayLoading = false
			                      },500)
							}
						})
						.catch(error=>{
			                 setTimeout(function(){
			                          that.displayLoading = false
			                  },500)
						})
					}
					else{
						modifyProject(this.form).then(res=>{
							if(res.data.flag == true){
								this.submitSuccess = true
								// this.$store.commit('cacheRoute',this.$store.state.cacheRoute.splice('item',1))
								this.$message({type:'success',message:res.data.msg})
							    this.$router.push({name:'item'})
							}
							else{
								setTimeout(function(){
			                          that.displayLoading = false
			                      },500)
							}
							
						})
						.catch(error=>{
			                 setTimeout(function(){
			                          that.displayLoading = false
			                  },500)
						})
					}
				}
	      	})
		},
		//编辑新增企业
		EditCompany(index,rowdata){
			this.$refs.addCompany.$emit('openEditDialog',rowdata,index)
		},
		//删除新增企业
		delCompany(index){
			this.common_del(index,this.company_list)
		},
		//新增参与企业
		joinCompanyAdd(){
			this.$refs.addCompany.$emit('openDialog')
		},
		companyFinished(arg){
			let that = this
			let com_list=arg[0];
			//对数据做处理  企业code  企业name
			[com_list.entCode,com_list.entName]=[arg[1].code,arg[1].entName]
			//企业账户 code和名称
			com_list.bizEntBankList=[
				// {
				// 	code:'',
				// 	name:''
				// }
			]
			//企业账户信息
			DetailCompany(com_list.entCode).then(response => {
				if(response.data.flag  == true){
					let data = response.data.data.bizEntBankList
					data.forEach((item)=>{
						com_list.bizEntBankList.push({bankAccount:item.bankAccount,accountName:item.accountName,subbranchName:item.subbranchName})
					})
					//编辑状态
					if(arg[2] != undefined){
					    let ind= arg[2]
					    this.company_list.splice(ind,1,com_list)
					}
					else{
						this.company_list.push(com_list)
					}
				}	
			})
		},
		//新增文件
		addFiles(){
		    this.$refs.addFile.$emit('openDialog')
		},
		//接收已经上传的文件，并返回列表
		recept(arg){
		    let  form = arg[0] 
		    form.forEach((item,index)=>{
		      this.filelist.push({fileName:item.name,fileCode:item.code})
		    })
		},
	    //删除文件（新增时删除）
	    fileDelete(index,row){
	      	this.common_del(index,this.filelist)
	    },
	    //增加相关角色
	    addRelatedUser(){
	    	this.$refs.relatedUser.$emit('openDialog',this.related_tags)
	    },
	    //添加相关角色完成
	    relatedFinish(data){
	    	this.related_tags=data
	    },
	    close_related(index){
	    	this.common_del(index,this.related_tags)
	    },
	    /*表单操作 submit & 新增企业 账户 文件 相关角色  E*/
     },
    mounted(){
		this.$nextTick(function () {
		})
	},
    components:{
     	FileEdit,
     	CompanyEdit,
     	relatedUserEdit
    },
    beforeRouteLeave(to,from,next){
    	/*提交时不需缓存*/
     	from.meta.modifyCacheRoute = this.submitSuccess == true ? true :false
     	next()
    }
}
</script>

<style  scoped>
/*名称规则命名*/
.rule_proName{color: #999;}
@media screen and (max-width: 1418px) {
    .el-input--suffix .el-input__inner{padding-right: 18px;}
}
/*新增项目 用户头像*/
.default-user-img{background: #eee;border-radius: 50%;}
</style>